const uuidv1 = require('uuid/v1')
const config = require('../config')
let sendMsgFlag = false

exports.listWaitOrders = async (Contract, access_token, UserId) => {
	let rs_error = null, rs = []
	const url = `https://www.chaobi.com:7443/rsporder/list?Contract=${Contract}&access_token=${access_token}&UserId=${UserId}`
	try {
		let {statusCode, body} = await Request.getAsync(url, {timeout: config.timeout, json: true})
		// console.log(1, statusCode, body)
		if (statusCode === 200 && body.data) {
			const orders = body.data
			// ["Received", "PartTradingQueueing", "AllTraded", "Canceled", "Error"]
			rs = orders.filter(item => item.OrderStatus == 'Received' || item.OrderStatus == 'PartTradingQueueing')
		}
	} catch (error) {
		rs_error = error
		LOG([error])
	}
	return [rs_error, rs]
}

exports.cancelOrder = async ({ClientOrderId, Side, InsertPrice, InsertVolume, access_token, UserId}) => {
	const url = 'https://www.chaobi.com:7443/order/cancel'
	const headers = { "content-type": "application/json"}
	const body = {access_token, UserId, ClientOrderId}
	let res = {}
	try {
		await Promise.delay(config.operationOrderGap)
		res = await Request.postAsync(url, {headers, body, json: true})
	} catch (error) {
		LOG([error])
	}
	// LOG([`cancel: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`])
}

exports.sendOrder = async ({Contract, Side, InsertPrice, InsertVolume, access_token, UserId}) => {
	const url = 'https://www.chaobi.com:7443/order/send'
	const ClientOrderId = uuidv1().replace(/-/g, '')
	const PriceType = 'Limit'

	const base = Contract.split('_')[0].toLowerCase()
	let PriceFixed = config.contractMap[base][0], VolumeFixed = config.contractMap[base][1]
	// console.log(Contract, base, PriceFixed, VolumeFixed, InsertPrice, InsertVolume)


	InsertPrice = InsertPrice.toFixed(PriceFixed)
	InsertVolume = InsertVolume.toFixed(VolumeFixed)
	let body = {access_token, UserId, ClientOrderId, Contract, Side, InsertPrice, InsertVolume, PriceType}
	const headers = { "content-type": "application/json"}
	let res = {}
	try {
		await Promise.delay(config.operationOrderGap)
		res = await Request.postAsync(url, {headers, body, json: true})
		LOG([Contract, `${Side}_price:`, InsertPrice, `${Side}_volume:`, InsertVolume, `result:`, res.statusCode, res.body.errCode])
	} catch (error) {
		LOG(['chaobi', error.code || error.message || error])
	}
	//TC_ORDER_SEND_MONEY_ERROR
	if (res.body && res.body.errCode === 'TC_ORDER_SEND_MONEY_ERROR') {
		if (!sendMsgFlag) {
			sendMsgFlag = true
			//send msg next
		}
	} else {
		if (Side === 'Sell' && res.body && res.body.errCode === 'TC_ORDER_SEND_SUCCESS') sendMsgFlag = false
	}
}

exports.market_order_price = async (base, quote) => {
	
	const Contract = `${base.toUpperCase()}_${quote.toUpperCase()}`
	let [ask_price, bid_price] = [0, 0]
	try {
		const {statusCode, body} = await Request.getAsync(`https://www.chaobi.com:6443/quotation/lastall`, {timeout: config.timeout, json: true})
		// console.log(statusCode, body)

		if (statusCode === 200 && body.data) {

			datas = body.data.filter(item => item.contract === Contract)[0].data
			datas = datas.split('`')
			const bids_ary = datas[1].split(',')
			const asks_ary = datas[3].split(',')

			ask_price = asks_ary[0]
			bid_price = bids_ary[0]
		}
		
	} catch (e) {
		LOG([e.code || e.message || e])
	}
	// console.log(market_name, ask_price, bid_price, ask_volume, bid_volume)
    return [ask_price, bid_price]
}